//
//  ContentView.swift
//  HealthClock
//
//  Created by 任建勇 on 2025/1/4.
//

import SwiftUI

struct ContentView: View {
    @StateObject private var timeManager: TimeManager
    @AppStorage("standingDuration") private var standingDuration: Double = 30
    @AppStorage("sittingDuration") private var sittingDuration: Double = 30
    @State private var isSettingsPresented = false
    
    init() {
        _timeManager = StateObject(wrappedValue: TimeManager(
            standingDuration: UserDefaults.standard.double(forKey: "standingDuration"),
            sittingDuration: UserDefaults.standard.double(forKey: "sittingDuration")
        ))
    }
    
    var body: some View {
        VStack(spacing: 15) {
            Text("\(timeManager.currentPosture.title)模式")
                .font(.title2)
            
            Text(timeManager.timeString())
                .font(.system(size: 36, weight: .bold, design: .monospaced))
            
            Button(action: timeManager.toggleTimer) {
                Text(buttonText)
                    .frame(width: 80)
            }
            .padding(.bottom, 5)
            
            Button(action: timeManager.switchPosture) {
                Text("切换\(timeManager.currentPosture.nextPosture.title)")
                    .frame(width: 80)
            }
            .foregroundColor(timeManager.currentPosture.nextPosture == .standing ? .green : .red)
            
            Button(action: { isSettingsPresented = true }) {
                Image(systemName: "gear")
                    .font(.title3)
            }
            .sheet(isPresented: $isSettingsPresented) {
                SettingsView(standingDuration: $standingDuration,
                           sittingDuration: $sittingDuration,
                           timeManager: timeManager)
            }
        }
        .padding(.horizontal, 8)
        .padding(.vertical, 6)
        .frame(width: 200, height: 220)
        .onAppear {
            setupNotifications()
        }
    }
    
    private var buttonText: String {
        if timeManager.timer == nil {
            return timeManager.isPaused ? "开始" : "恢复"
        } else {
            return "暂停"
        }
    }
    
    private func setupNotifications() {
        NotificationManager.shared.requestPermission { granted, error in
            if granted {
                print("通知权限已获取")
            } else if let error = error {
                print("获取通知权限失败: \(error.localizedDescription)")
            }
        }
        
        NotificationCenter.default.addObserver(
            forName: .notificationTapped,
            object: nil,
            queue: .main) { [weak timeManager] _ in
                print("通知被点击")
                timeManager?.switchPosture()
                
                // 延迟一小段时间后隐藏窗口，确保在系统尝试激活窗口之后执行
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                    print("准备隐藏窗口")
                    // 只隐藏主窗口，不隐藏整个应用
                    if let window = NSApp.windows.first {
                        print("隐藏窗口: \(window)")
                        window.orderOut(nil)
                    }
                }
            }
    }
}

#Preview {
    ContentView()
}
